//
//  PlayerView.m
//  Exam10-2
//
//  Created by 孙晓晔 on 2017/4/11.
//  Copyright © 2017年 孙晓晔. All rights reserved.
//

#import "PlayerView.h"

#define ItemStatus @"status"
#define ItemLoad @"loadedTimeRanges"

@interface PlayerView()
@property (weak, nonatomic) IBOutlet UIButton *playBtn; // 播放
@property (weak, nonatomic) IBOutlet UIButton *pauseBtn; // 暂停
@property (weak, nonatomic) IBOutlet UIButton *stopBtn; // 停止
@property (weak, nonatomic) IBOutlet UIButton *screenBtn; // 全屏
@property (weak, nonatomic) IBOutlet UISlider *slider; // 进度
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;

@property (weak, nonatomic) IBOutlet UILabel *currentTime; // 当前时间
@property (weak, nonatomic) IBOutlet UILabel *totalTime; // 总时长

@property(nonatomic,strong) NSTimer *timer1; // 定时器
@property(nonatomic, assign) CGRect size;
@end

@implementation PlayerView

// 初始化
-(instancetype)init {
    
    self = [[[NSBundle mainBundle] loadNibNamed:@"PlayerView" owner:nil options:nil] firstObject];
    
    if (self) {
    }
    
    return self;
}

// 屏幕旋转时重设
-(void)resetFrame:(CGSize)size {
    
    self.frame = CGRectMake(0, 0, size.width, size.height);
    self.playLayer.bounds = CGRectMake(0, 0, size.width, 240);
    self.playLayer.position = CGPointMake(0, 0);
    
}

// 懒加载
-(AVPlayerLayer *)playLayer {
    if (_playLayer == nil) {
        _playLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
        
        _playLayer.backgroundColor = [UIColor blackColor].CGColor;
        _playLayer.bounds = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 240);
        
        _playLayer.anchorPoint = CGPointMake(0, 0);
        _playLayer.position = CGPointMake(0, 0);
        
        [self.layer addSublayer:_playLayer];
    }
    
    return _playLayer;
}

-(void)playerWithURL:(NSURL*)URL {
    
    self.player = [AVPlayer playerWithURL:URL];
        
    [self.player.currentItem addObserver:self forKeyPath:ItemStatus options:NSKeyValueObservingOptionNew context:nil];
        
    [self.player.currentItem addObserver:self forKeyPath:ItemLoad options:NSKeyValueObservingOptionNew context:nil];
    
    [self playLayer];
    
    self.stopBtn.enabled = FALSE;
    self.pauseBtn.enabled = FALSE;
    self.playBtn.enabled = TRUE;
}

// 观察KVO
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    
    if ([keyPath isEqualToString:ItemStatus]) {
        AVPlayerItem *item = object;
        
        if (item.status == AVPlayerItemStatusReadyToPlay) {
            
            long long llsecond = item.duration.value / item.duration.timescale;
            
            self.totalTime.text = [self formatTime:llsecond];
            
            self.slider.minimumValue = 0;
            self.slider.maximumValue = llsecond;
            
            __weak typeof (self) weakSelf = self;
            
            [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:NULL usingBlock:^(CMTime time) {
                weakSelf.slider.value = weakSelf.player.currentItem.currentTime.value / weakSelf.player.currentItem.currentTime.timescale;
                
                CMTime ctime = weakSelf.player.currentItem.currentTime;
                
                weakSelf.currentTime.text = [weakSelf formatTime:(ctime.value/ctime.timescale)];
                
            }];
            
            NSLog(@"AVPlayerItemStatusReadyToPlay");
        } else if(item.status == AVPlayerItemStatusFailed) {
            NSLog(@"AVPlayerItemStatusFailed");
        } else if(item.status == AVPlayerItemStatusUnknown) {
            
            NSLog(@"AVPlayerItemStatusUnknown");
        }
    } else if ([keyPath isEqualToString:ItemLoad]) {
        AVPlayerItem *item = object;
        
        long long llTotalSecond = item.duration.value / item.duration.timescale;
        
        NSValue *value = [item.loadedTimeRanges lastObject];
        CMTimeRange range = [value CMTimeRangeValue];
        long long llsecond = range.start.value / range.start.timescale + range.duration.value / range.duration.timescale;
        
        [self.progressView setProgress:((float)llsecond/llTotalSecond) animated:YES];
    }
}

// 重写，释放
-(void)dealloc {
    
    [self.player.currentItem removeObserver:self forKeyPath:ItemStatus];
    [self.player.currentItem removeObserver:self forKeyPath:ItemLoad];
}

-(void)timerOn {
    self.timer1 = [NSTimer scheduledTimerWithTimeInterval:0.3 repeats:YES block:^(NSTimer * _Nonnull timer) {
        
    }];
}

-(void)timerOff {
    [self.timer1 invalidate];
    self.timer1 = nil;
}

// 时间格式化
-(NSString*)formatTime:(NSTimeInterval)time {
    NSInteger second = (NSInteger)time;
    
    NSInteger minute = 0;
    if (second > 60) {
        minute = second / 60;
        second = second % 60;
    }
    
    NSString *ret = [NSString stringWithFormat:@"%02ld:%02ld", minute, second];
    
    return ret;
}

- (IBAction)slider:(UISlider *)sender {
    
    CMTime changedTime = CMTimeMakeWithSeconds(sender.value, 1);
    
    __weak typeof(self) weakSelf = self;
    [self.player seekToTime:changedTime completionHandler:^(BOOL finished) {
        [weakSelf.player play];
    }];
}

// 播放
- (IBAction)play:(UIButton *)sender {
    self.playBtn.enabled = FALSE;
    
    self.stopBtn.enabled = TRUE;
    self.pauseBtn.enabled = TRUE;
    
    [self.player play];
}

// 暂停
- (IBAction)pause:(UIButton *)sender {
    self.pauseBtn.enabled = FALSE;
    
    self.stopBtn.enabled = TRUE;
    self.playBtn.enabled = TRUE;
    
    [self.player pause];
}

// 停止
- (IBAction)stop:(UIButton *)sender {
    
    self.stopBtn.enabled = FALSE;
    self.pauseBtn.enabled = FALSE;
    self.playBtn.enabled = TRUE;
    
    self.player.rate = 0;
    
    [self.player.currentItem seekToTime:CMTimeMake(0, 1)];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    _playLayer.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 240);
}
// 全屏
- (IBAction)screen:(UIButton *)sender {
//    CGFloat width = [UIScreen mainScreen]
    _playLayer.frame = [UIScreen mainScreen].bounds;
    //_playLayer.position =
}


@end
